let FloatyUtil = function () {
  this.floatyWindow = null;
  this.floatyInitStatus = false;
  this.floatyLock = threads.lock();
  this.floatyCondition = this.floatyLock.newCondition();
};

FloatyUtil.prototype.init = function () {
  if (this.floatyInitStatus) {
    return;
  }
  let _this = this;
  threads.start(function () {
    _this.floatyLock.lock();
    try {
      if (_this.floatyInitStatus) {
        return;
      }
      _this.floatyWindow = floaty.rawWindow(
        <frame gravity="left">
          <text id="content" textSize="16dp" textColor="#00ff00" bg="#000000" alpha="0.6" />
        </frame>
      );
      ui.run(function () {
        _this.floatyWindow.setTouchable(false);
        _this.floatyWindow.setPosition(50, 350);
        _this.floatyWindow.content.text("悬浮窗初始化成功");
      });
      _this.floatyInitStatus = true;
    } catch (e) {
      console.error("悬浮窗初始化失败" + e);
      _this.floatyWindow = null;
      _this.floatyInitStatus = false;
    } finally {
      _this.floatyCondition.signalAll();
      _this.floatyLock.unlock();
    }
  });
  _this.floatyLock.lock();
  try {
    if (_this.floatyInitStatus === false) {
      console.info("等待悬浮窗初始化");
      _this.floatyCondition.await();
    }
  } finally {
    _this.floatyLock.unlock();
  }
};

FloatyUtil.prototype.setInfo = function (text, position, option) {
  option = option || {};
  if (this.floatyWindow === null) {
    this.init();
  }
  let _this = this;
  ui.run(function () {
    _this.floatyLock.lock();
    try {
      if (position && isFinite(position.x) && isFinite(position.y)) {
        _this.floatyWindow.setPosition(parseInt(position.x), parseInt(position.y) + 100);
      }
      if (text) {
        _this.floatyWindow.content.text(text);
        log(text);
      }
      if (option.textSize) {
        _this.floatyWindow.content.setTextSize(option.textSize);
      }
      if (typeof option.touchable !== "undefined") {
        _this.floatyWindow.setTouchable(option.touchable);
      }
    } finally {
      _this.floatyLock.unlock();
    }
  });
};
module.exports = new FloatyUtil();
